package com.carful.xigua.modules.xigua.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.carful.xigua.modules.common.util.JwtUtils;
import com.carful.xigua.modules.common.util.SecurityContextUtils;
import com.carful.xigua.modules.user.entity.Org;
import com.carful.xigua.modules.user.entity.Role;
import com.carful.xigua.modules.user.entity.User;
import com.carful.xigua.modules.user.entity.UserRole;
import com.carful.xigua.modules.user.service.impl.*;
import com.carful.xigua.modules.xigua.service.impl.SystemServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;

/**
 * xigua
 * @author ad
 * Date 2024/7/12 11:49
 */


@Slf4j
@RestController
@RequestMapping("/xigua")
public class XiguaController {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private SystemServiceImpl systemService;
    @Autowired
    private OrgServiceImpl orgService;
    @Autowired
    private UserRoleServiceImpl userRoleService;
    @Autowired
    private RoleServiceImpl roleService;
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * code领取西瓜
     * @param code
     * @return
     */
    @PreAuthorize("@CompositePermissionAny.preHandle(null)")
    @GetMapping("/xigua")
    public String getXigua(@RequestParam("code") String code) {
        // 解析code
        try {

            String[] split = code.split("-");
            Long stamp = Long.parseLong(split[1]);
            long l = System.currentTimeMillis();
            if (l <= stamp) throw new RuntimeException("二维码错误");
            if (l - stamp > 1000L * 60 * 5) throw new RuntimeException("二维码过期");
            User user = SecurityContextUtils.getLoginUserDetails().getUser();
            return userService.getXigua(split[0], user);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("二维码错误");
        }
    }
    @Deprecated
    @PreAuthorize("@CompositePermissionAny.preHandle(null)")
    @PostMapping("/info")
    public String info() {
        List<User> list = userService.list();
        for (User user : list) {
//            userService.info(user);
            if (user.getCnt() == null) {
                user.setCnt(0);
            }
            if (user.getCurrentCnt() == null) {
                user.setCurrentCnt(user.getCnt());
            }
            userService.updateById(user);
            log.info("更新，{}", user.getUsername());
        }
        return "";
    }

    @Deprecated
    @PreAuthorize("@CompositePermissionAny.preHandle(null)")
    @PostMapping("/addUser")
    public String addUser() throws Exception {

        BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\out.txt"));
        List<String> lists = getDataLine(bufferedReader);

        HashSet<String> hashSet = new HashSet<>();

        int count = 0;
        Role role = roleService.getOne(new LambdaQueryWrapper<Role>().eq(Role::getValue, "admin"));
        for (String s : lists) {
            String[] split = s.split("\t");
            String orgName = split[0];
            String name = split[1];
            String phone = split[2];
            hashSet.add(phone);
            Org org = orgService.getOne(new LambdaQueryWrapper<Org>().eq(Org::getName, orgName));
            if (org == null) {
                org = new Org();
                org.setName(orgName);
                orgService.save(org);
            }
            User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, phone));
            if (user == null) {
                user = new User();
                user.setUsername(phone);
                user.setUserPhone(phone);
                user.setOrgId(org.getId());
                user.setPassword(passwordEncoder.encode(phone));
                boolean save = userService.save(user);
                if (save) ++count;
            } else {
                User user1 = new User();
                user1.setId(user.getId());
                user1.setPassword(passwordEncoder.encode(phone));
                boolean update = userService.updateById(user1);
                if (update) ++count;
            }
            try {
                boolean save = userRoleService.save(new UserRole().setUserId(user.getId()).setRoleId(role.getId()));
            } catch (Exception e) {

            }
        }
        log.info("共有数据 {}", hashSet.size());
        log.info("插入数据 {}", count);
        return "";
    }

    /**
     * 处理 input 格式
     * @param bufferedReader
     * @return
     * @throws Exception
     */
    public List<String[]> getData(BufferedReader bufferedReader) throws Exception {
        List<String[]> lists = new ArrayList<>();
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            lists.add(str.split("[ ]"));
        }
        bufferedReader.close();
        return lists;
    }
    public static List<String> getDataLine(BufferedReader bufferedReader) throws Exception {
        List<String> lists = new ArrayList<>();
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            lists.add(str);
        }
        bufferedReader.close();
        return lists;
    }
}
